<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @submit="handlerSearch" @reset="resetSearch" />

    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="920"
    >
      <template #tableTitle>
        <n-popconfirm
          @positive-click="deleteLogHandler"
        >
          <template #trigger>
            <n-button type="error">
              <template #icon>
                <n-icon>
                  <Trash />
                </n-icon>
              </template>
              删除/批量删除
            </n-button>
          </template>
          确定删除数据？
        </n-popconfirm>

      </template>
      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <n-modal
      v-model:show="showDetailModel"
      class="custom-card"
      preset="card"
      :style="{ width: '700px' }"
      title="日志详情"
      size="huge"
      :bordered="false"
    >
      <template #header-extra>
        <n-tag type="info">
          操作用户 / IP : {{ detailModelInfo['requestUsername'] || '未登录' }} / {{ detailModelInfo['requestIp'] }}
        </n-tag>
      </template>

      <n-list hoverable>
        <n-list-item>
          <template #prefix>
            <n-tag type="info">调用信息</n-tag>
          </template>
          <n-thing :title="detailModelInfo['methodName']">
            {{ detailModelInfo['methodDesc'] }}
          </n-thing>
        </n-list-item>
        <n-list-item>
          <template #prefix>
            <n-tag type="info">请求信息</n-tag>
          </template>
          <n-thing :title="`${detailModelInfo['requestMethod']}  ${detailModelInfo['requestUrl']}`">
            data => {{ detailModelInfo['requestData'] }}
          </n-thing>
        </n-list-item>
        <n-list-item>
          <template #prefix>
            <n-tag type="info">响应数据</n-tag>
          </template>
          <n-thing :title="detailModelInfo['responseResult'] || '无响应数据'" />
        </n-list-item>
      </n-list>
      <template #footer>
        <n-space size="medium">
          <n-tag type="info" v-if="detailModelInfo['processTime'] === 0">执行时间: 未记录</n-tag>
          <n-tag type="info" v-else>执行时间: {{ detailModelInfo['processTime'] }} ms</n-tag>
          <n-tag type="info">记录时间: {{ detailModelInfo['createTime'] }}</n-tag>
          <n-tag type="success">地理位置: {{ detailModelInfo['requestLocation'] }}</n-tag>
        </n-space>
      </template>
    </n-modal>

  </n-card>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import { useMessage } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { getLogPage, deleteLogs, deleteLog } from '@/api/system/log'
import { Trash, Search } from '@vicons/ionicons5';
import { useRouter } from 'vue-router';
import { NTag, NButton } from "naive-ui";
import { useGlobSetting } from "@/hooks/setting";
import { ResultEnum } from "@/enums/httpEnum";

const global = useGlobSetting()
const message = useMessage()

const schemas: FormSchema[] = [
  {
    field: 'name',
    labelMessage: '注意哦, 不是用户昵称',
    component: 'NInput',
    label: '用户名',
    componentProps: {
      placeholder: '输入用户名',
      onInput: (e: any) => {
        searchForm.username = e;
      },
    },
  },
  {
    field: 'ip',
    component: 'NInput',
    label: '主机',
    componentProps: {
      placeholder: '输入主机IP地址',
      onInput: (e: any) => {
        searchForm.ip = e;
      },
    },
  },
  {
    field: 'code',
    component: 'NSelect',
    label: '响应状态码',
    componentProps: {
      placeholder: '选择响应状态',
      options: function (): {label, value}[] {
        let arr: {label, value}[] = []
        for(let label in ResultEnum) {
          let keyToAny: any = label;
          if(!isNaN(keyToAny)) {
            arr.push({ label, value: ResultEnum[label] })
          }
        }
        return arr
      }(),
      onUpdateValue: (e: any) => {
        searchForm.code = e;
      },
    },
  },
  {
    field: 'range',
    component: 'NDatePicker',
    label: '记录时间',
    defaultValue: null,
    componentProps: {
      type: 'daterange',
      clearable: true,
      onUpdateFormattedValue: (e: any) => {
        searchForm.startTime = e[0]
        searchForm.endTime = e[1]
      },
    },
  },
];
// 按需搜索表单
const searchForm = reactive({
  username: null,
  ip: null,
  code: null,
  startTime: null,
  endTime: null
})

const [register, {}] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:3 2xl:3' },
  labelWidth: 90,
  schemas,
});

const handlerSearch = () => {
  reloadTable()
}

const resetSearch = () => {
  searchForm.username = searchForm.ip = searchForm.code = searchForm.startTime = searchForm.endTime = null
  reloadTable()
}

// 表格数据
const columns = [
  {
    type: 'selection'
  },
  {
    title: '序号',
    key: 'id',
    width: 50,
    align: 'center',
  },
  {
    title: '方法描述',
    key: 'methodDesc',
    width: 100,
    align: 'center',
  },
  {
    title: '请求用户',
    key: 'requestUsername',
    width: 80,
    align: 'center',
    render(row) {
      return h('span', {}, { default: () => row?.requestUsername || '无登录' })
    }
  },
  {
    title: '主机',
    key: 'requestIp',
    width: 80,
    align: 'center',
  },
  {
    title: '处理时长',
    key: 'processTime',
    width: 70,
    align: 'center',
    render: (row) => {
      return h(NTag, {
        type: 'info'
      }, {
        default: () => {
          if (row.processTime === 0) {
            return '未记录'
          } else if (row.processTime > 1000) {
            return `${Math.ceil(row.processTime/100)/10} s`
          } else {
            return `${row.processTime} ms`
          }
        }
      });
    }
  },
  {
    title: '状态码',
    key: 'responseCode',
    width: 70,
    align: 'center',
    render: (row) => {
      return h(NTag, {
        type: String(row.responseCode).startsWith('2') ? 'success' : 'error'
      }, { default: () => `${row.responseCode}` });
    }
  },
  {
    title: '记录时间',
    key: 'createTime',
    width: 160,
    align: 'center',
  }
];

const router = useRouter();
const formRef: any = ref(null);
// const message = useMessage();
const actionRef = ref();

const actionColumn = reactive({
  width: 100,
  title: '操作',
  key: 'action',
  fixed: 'right',
  align: 'center',
  render(row) {
    return h(TableAction, {
      style: 'text',
      actions: [
        {
          label: '查看详情',
          type: 'info',
          icon: Search,
          onClick: () => {
            detailModelInfo.value = row
            showDetailModel.value = true;
          }
        },
      ],
    });
  }
});

const showDetailModel = ref(false)
const detailModelInfo = ref()

const loadDataTable = async (res) => {
  let params = {}
  if (searchForm.username) params['username'] = searchForm.username
  if (searchForm.ip) params['ip'] = searchForm.ip
  if (searchForm.code) params['code'] = searchForm.code
  if (searchForm.startTime) params['startTime'] = searchForm.startTime
  if (searchForm.endTime) params['endTime'] = searchForm.endTime
  const data = await getLogPage({ pageNumber: res.current, pageSize: res.size }, params);
  // total 指的是总共多少条数据
  const { current, size, total, records } = data;
  return {
    current,
    size,
    count: Math.ceil(total / size),
    records,
  };
};

const checkRows = ref([])

function onCheckedRow(rowKeys) {
  checkRows.value = rowKeys
}

const deleteLogHandler = async () => {
  if (checkRows.value.length === 0) {
    message.warning('没有删除的数据为什么要点我呢？')
    return
  }
  if (checkRows.value.length === 1) {
    let id = checkRows.value[0]
    await deleteLog(id)
    checkRows.value = []
    reloadTable()
    return
  }
  await deleteLogs(checkRows.value)
  checkRows.value = []
  reloadTable()
}

function reloadTable() {
  actionRef.value.reload();
}

</script>

<style lang="less" scoped></style>
